//
//  MPMoviePlayerView.m
//  MPMoviePlayerTest
//
//  Created by mac mini 20 on 1/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MPMoviePlayerView.h"

static MPMoviePlayerController *shareMoviePlayer = nil;

@implementation MPMoviePlayerView

+ (id)shareMoviePlayer
{
	if (!shareMoviePlayer) {
		shareMoviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: nil];;
	}
	return shareMoviePlayer;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor blackColor];
        
        // setup MPMoviePlayerController
        shareMoviePlayer = [MPMoviePlayerView shareMoviePlayer];
        shareMoviePlayer.scalingMode = MPMovieScalingModeAspectFit;
        shareMoviePlayer.controlStyle = MPMovieControlStyleEmbedded; //MPMovieControlStyleFullscreen; 
        
        shareMoviePlayer.shouldAutoplay = NO; //not automatically start playback
        //shareMoviePlayer.shouldAutoplay = YES;
        
        /* Register observers for the various movie object notifications. */
        // Register for the playback finished notification
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(myMovieFinishedCallback:)
                                                     name: MPMoviePlayerPlaybackDidFinishNotification object: shareMoviePlayer];
        
        // right/left swipe gesture
        UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
        [self addGestureRecognizer:swipeRecognizer];
        [swipeRecognizer release]; swipeRecognizer = nil;
         
        swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
        swipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
        [self addGestureRecognizer:swipeRecognizer];
        [swipeRecognizer release]; swipeRecognizer = nil;
        
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor blackColor];
        
        // setup MPMoviePlayerController
        shareMoviePlayer = [MPMoviePlayerView shareMoviePlayer];
        shareMoviePlayer.scalingMode = MPMovieScalingModeAspectFit;
        shareMoviePlayer.controlStyle = MPMovieControlStyleEmbedded; //MPMovieControlStyleFullscreen; 
        
        shareMoviePlayer.shouldAutoplay = NO; //not automatically start playback
        //shareMoviePlayer.shouldAutoplay = YES;
        
        /* Register observers for the various movie object notifications. */
        // Register for the playback finished notification
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(myMovieFinishedCallback:)
                                                     name: MPMoviePlayerPlaybackDidFinishNotification object: shareMoviePlayer];
        
        // right/left swipe gesture
        UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
        [self addGestureRecognizer:swipeRecognizer];
        [swipeRecognizer release]; swipeRecognizer = nil;
        
        swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
        swipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
        [self addGestureRecognizer:swipeRecognizer];
        [swipeRecognizer release]; swipeRecognizer = nil;
        
    }
    return self;
}

- (void)dealloc
{
    /* Remove the movie notification observers from the movie object. */
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:shareMoviePlayer];
    
    [urlArray release];
    [super dealloc];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

// helper
-(void)createAndConfigurePlayerWithURL:(NSURL *)theURL sourceType:(MPMovieSourceType)movieSourceType 
{
    // setup MPMoviePlayerController
    shareMoviePlayer = [MPMoviePlayerView shareMoviePlayer];
    //shareMoviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:theURL];
    shareMoviePlayer.scalingMode = MPMovieScalingModeAspectFit;
    shareMoviePlayer.controlStyle = MPMovieControlStyleEmbedded; //MPMovieControlStyleFullscreen; 
    
    shareMoviePlayer.shouldAutoplay = NO; //not automatically start playback
    //shareMoviePlayer.shouldAutoplay = YES;
    
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    shareMoviePlayer.view.frame = CGRectMake(0., 0., width, height); 
    
//        // set backgroundView of player
//        UIImage *imgBk = [UIImage imageNamed:@"bk.png"];
//        UIImageView *imgViewBk = [[UIImageView alloc] initWithImage:imgBk];
//        CGFloat widthBk = imgBk.size.width;
//        CGFloat heightBk = imgBk.size.height;
//        NSInteger xBk = 0; 
//        NSInteger yBk = 0;
//        // in middle. limit size
//        if (widthBk < width) {
//            xBk = (width-widthBk)/2; // x middle
//        }
//        else {
//            widthBk = width; // max width
//        }
//        if (heightBk < height) {
//            yBk = (height-heightBk)/2; // y middle
//        }
//        else {
//            heightBk = height; // max height
//        }
//        imgViewBk.frame = CGRectMake(xBk, yBk, widthBk, heightBk);
//        [player.backgroundView addSubview:imgViewBk];
//        [imgViewBk release]; imgViewBk = nil;
    
    [self addSubview:[shareMoviePlayer view]];
    
    shareMoviePlayer.contentURL = theURL; // Note: must first addSubview, then set contentURL. 
    //shareMoviePlayer.movieSourceType = movieSourceType;  // error bug
}

- (void) playMovieAtURL: (NSURL*) theURL 
{
    // check url
    if (theURL==nil) {
        shareMoviePlayer.contentURL = nil;
        return ;
    }
    
//    // movie source type
//    MPMovieSourceType movieSourceType = MPMovieSourceTypeUnknown;
//    /* If we have a streaming url then specify the movie source type. */
//    if ([[theURL pathExtension] compare:@"m3u8" options:NSCaseInsensitiveSearch] == NSOrderedSame) 
//    {
//        movieSourceType = MPMovieSourceTypeStreaming;
//    }
//    
//    if(shareMoviePlayer==nil) {
//        [self createAndConfigurePlayerWithURL:theURL sourceType:movieSourceType];
//        
//        /* Register observers for the various movie object notifications. */
//        // Register for the playback finished notification
//        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(myMovieFinishedCallback:)
//                                                     name: MPMoviePlayerPlaybackDidFinishNotification object: shareMoviePlayer];
//    }
//    else {
//        shareMoviePlayer.contentURL = theURL;
//        shareMoviePlayer.movieSourceType = movieSourceType;
//    }
    
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    shareMoviePlayer.view.frame = CGRectMake(0., 0., width, height); 
    
    [self addSubview:[shareMoviePlayer view]];
    
    shareMoviePlayer.contentURL = theURL; // Note: must first addSubview, then set contentURL. 
    //shareMoviePlayer.movieSourceType = movieSourceType;  //error bug

    // Movie playback is asynchronous
    //[shareMoviePlayer play];
    
    if (shareMoviePlayer.playbackState == MPMoviePlaybackStatePlaying) {
        [shareMoviePlayer stop];
    }
    else {
        [shareMoviePlayer prepareToPlay];
    }
}

- (void) playMovieWithURLArray: (NSArray*)urlArrayNew withIndex:(NSUInteger)indexNew
{
    // check
    if ([urlArrayNew count]<=indexNew)
        return;
    
    [urlArrayNew retain];
    [urlArray release];
    urlArray = urlArrayNew;
    
    index = indexNew;
    
    // 
    NSURL *urlNew = [urlArray objectAtIndex:indexNew];
    if (![shareMoviePlayer.contentURL isEqual:urlNew]) {
        // play new url
        [self playMovieAtURL:urlNew];
    }
}

#pragma mark handle MPMoviePlayerController notification callback
// When the movie is done, release the controller.
- (void) myMovieFinishedCallback: (NSNotification*)notification
{
//    NSLog(@"myMovieFinishedCallback notification"); //test
//    MPMoviePlayerController *thePlayer = [notification object];
    
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:thePlayer];
//    [thePlayer.view removeFromSuperview];

    // Release the movie instance created in playMovieAtURL:
//    [thePlayer release];
    
    // begin
    //[thePlayer setCurrentPlaybackTime:0];
    
    NSNumber *reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]; 
	switch ([reason integerValue]) 
	{
            /* The end of the movie was reached. */
		case MPMovieFinishReasonPlaybackEnded:
            //play next video if have
            if (!changedBySwipe && [urlArray count] > index+1) {
                index ++;
                [self playMovieAtURL:[urlArray objectAtIndex:index]];
            } 
			break;
            
            /* An error was encountered during playback. */
		case MPMovieFinishReasonPlaybackError:
            NSLog(@"An error was encountered during playback");
//            [self performSelectorOnMainThread:@selector(displayError:) withObject:[[notification userInfo] objectForKey:@"error"] 
//                                waitUntilDone:NO];
			break;
            
            /* The user stopped playback. */
		case MPMovieFinishReasonUserExited:
			break;
            
		default:
			break;
	} // switch
    
    if (changedBySwipe) {
        changedBySwipe = NO;  //reset
    }
    
}

#pragma mark handle swipe gesture
- (void)handleSwipe:(UISwipeGestureRecognizer *)recognizer 
{
    NSUInteger countURL = [urlArray count];
    if (changedBySwipe || countURL<2)
        return;   
    
    changedBySwipe = NO;
    if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        //play prev video if have
        if (countURL > index-1) {
            changedBySwipe = YES;
            index --;
            [self playMovieAtURL:[urlArray objectAtIndex:index]];
        } //if
    }
    else {
        //play next video if have
        if (countURL > index+1) {
            changedBySwipe = YES;
            index ++;
            [self playMovieAtURL:[urlArray objectAtIndex:index]];
        } //if
    }
	
}

#pragma mark single tap
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer 
{
    NSLog(@"single tap\n");
    if (shareMoviePlayer.playbackState == MPMoviePlaybackStatePlaying) {
        [shareMoviePlayer pause];
    }
    else {
        [shareMoviePlayer play];
    }
}

#pragma mark Error Reporting
-(void)displayError:(NSError *)theError
{
	if (theError)
	{
		UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle: @"Error"
                              message: [theError localizedDescription]
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return NO;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (shareMoviePlayer.playbackState == MPMoviePlaybackStatePlaying) {
        [shareMoviePlayer pause];
    }
    else {
        [shareMoviePlayer play];
    }
    
    [super touchesEnded:touches withEvent:event];
}

@end
